package com.tgy.demo;

import com.tgy.demo.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

/***
 * @ClassName: testLogin
 * @Description:
 * @Auther: 送一一块二向箔
 * @Date: 23:30 2021/11/29
 * @version : V1.0
 */
public class testLogin {
    public static void main(String[] args) {
        loginPre("lisi","123456");
        //login("lisi' or '1=1","123456");
    }
    public static void login(String username,String password){
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcUtils.getConnection();
            statement = connection.createStatement();
            StringBuffer stringBuffer = new StringBuffer("select * from users where");
            stringBuffer.append("`name` = '" );
            stringBuffer.append(username);
            stringBuffer.append("'");
            stringBuffer.append("and `password` = '");
            stringBuffer.append(password);
            stringBuffer.append("'");
            resultSet = statement.executeQuery(stringBuffer.toString());
            while (resultSet.next()){
                System.out.println(resultSet.getString("name"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(connection,statement,resultSet);
        }
    }

    public static void loginPre(String username,String password){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcUtils.getConnection();
            //PreparedStatement 防止SQL注入的本质就是把传递进来的参数当作字符
            String sql = "SELECT* from `users`  where `name` = ? and `password` = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,username);
            statement.setString(2,password);
            resultSet = statement.executeQuery();
            while (resultSet.next()){
                System.out.println(resultSet.getString("name"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(connection,statement,resultSet);
        }
    }
}
